package com.xiangxiangjd.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiangxiangjd.bean.Goods;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.bean.DateNo;
import com.xiangxiangjd.idworker.Sid;
import com.xiangxiangjd.mapper.DateNoMapper;
import com.xiangxiangjd.service.DateNoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangxiangjd.bean.result.ResultPage;
import com.xiangxiangjd.controller.model.ApiResultModel;

import com.xiangxiangjd.service.GoodsService;
import com.xiangxiangjd.service.SysDictService;
import com.xiangxiangjd.utils.OddNumber;
import com.xiangxiangjd.utils.StringUtilsXiao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 添加退役航材的单号 服务实现类
 *
 * @author 肖守凯
 * @since 2021-11-08
 */
@Service
public class DateNoServiceImpl extends ServiceImpl<DateNoMapper, DateNo> implements DateNoService {

  @Autowired private GoodsService goodsService;

  @Autowired private SysDictService sysDictService;

  @Autowired private Sid sid;

  /**
   * 添加DateNo
   *
   * @param dateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Override
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  public ApiResultModel addDateNo(DateNo dateNo) {

    if (dateNo.getId() != null) {

      List<Goods> list =
          goodsService.list(new LambdaQueryWrapper<Goods>().eq(Goods::getDateNoId, dateNo.getId()));

      List<String> collect = list.stream().map(Goods::getId).collect(Collectors.toList());

      goodsService.delGoodss(collect);

    } else {
      // 查询最后一次插入的单号
      String lastOddNumber = baseMapper.getLastOddNumber();
      // 生成新的单号
      String newOddNumber = OddNumber.getOddNumber("HC", lastOddNumber);
      dateNo.setOddNumber(newOddNumber);
    }

    // 单号生成
    if (!this.saveOrUpdate(dateNo)) {
      return $.error("添加失败 日期单号生成失败");
    }

    // 获取航材信息
    List<Goods> goodsList = dateNo.getGoodsList();

    // System.out.println(goodsList.subList(0,10));

    // 校验字符串是否为数字
    goodsList.forEach(
        o -> {
          if (!StringUtilsXiao.isNumeric(o.getNumber())
              || !StringUtilsXiao.isNumeric(o.getPrice())) {
            throw new RuntimeException("请查看数量填写是否为整数， 单价填写是否为小数或者整数！");
          }
          if (StringUtilsXiao.isBlank(o.getEntityImgUrl())) {
            throw new RuntimeException("请上传实体图片！");
          }
          if (StringUtilsXiao.isBlank(o.getGoodsName())) {
            throw new RuntimeException("请填写资产名称！");
          }

          if (StringUtilsXiao.isBlank(o.getCompany())) {
            throw new RuntimeException("请填写计量单位！");
          }

          if (StringUtilsXiao.isBlank(o.getModel())) {
            throw new RuntimeException("请填写规格型号！");
          }

          if (StringUtilsXiao.isBlank(o.getEntityImgUrl())) {
            throw new RuntimeException("请上传实体图片！");
          }
          // 关联单号
          o.setDateNoId(dateNo.getId());

          // 判断是否航材
          if (o.getGoodsType().equals("1")) {

            if (Integer.valueOf(o.getNumber()) != 1) {
              throw new RuntimeException("航材数量必须为 1 件");
            }

          } else {
            // 耗材
            if (Double.valueOf(o.getNumber()) < 1 && Double.valueOf(o.getNumber()) > 10000) {
              throw new RuntimeException("耗材数量不小于 1 件 并且不大于10000");
            }
          }
          // 耗材的初始值
          Double aDouble = Double.valueOf(o.getNumber());
          o.setUserId("0");
          o.setInitNumber(aDouble);
          // o.setId(sid.nextShort());
        });

    System.out.println("一共累计：" + goodsList.size());
//    if (goodsList.size() / 1000 > 1) {
//      for (int i = 0; i < goodsList.size() / 1000; i++) {
//        int row;
//
//        if (i == goodsList.size() / 1000-1) {
//
//          row = goodsService.insertBatch(goodsList.subList(i*1000, goodsList.size()));
//        } else if (i == 0) {
//          row = goodsService.insertBatch(goodsList.subList(i, (i + 1) * 1000));
//        } else {
//          row = goodsService.insertBatch(goodsList.subList(i*1000, (i + 1) * 1000));
//        }
//
//        if (row < 1) {
//          return $.error("插入失败 请重新插入");
//        }
//      }
//    } else {
//    int  row = goodsService.insertBatch(goodsList.subList(0, goodsList.size()));
//
//      if (row < 1) {
//        return $.error("插入失败 请重新插入");
//      }
//
//    }

    // 插入航材详细信息
        boolean b = goodsService.saveOrUpdateBatch(goodsList);


        //goodsService.saveOrUpdateBatch()

        if (!b) {
          return $.error("插入失败 请重新插入");
        }

    return $.success("插入成功");
  }
  /**
   * 编辑跳转页面的回显数据DateNo
   *
   * @param id 前端传进的参数
   * @return 返回实体类
   */
  @Override
  public DateNo selectDateNoByIdDateNo(Integer id) {
    return baseMapper.getByIdAllFixed(id);
  }

  /**
   * 编辑DateNo
   *
   * @param dateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel editDateNo(DateNo dateNo) {

    if (dateNo.getId() == null) {
      throw new RuntimeException("请查看单号 是否携带id");
    }

    // 单号生成
    if (!this.saveOrUpdate(dateNo)) return $.error("添加失败 日期单号生成失败");

    // 获取航材信息
    List<Goods> goodsList = dateNo.getGoodsList();

    // 校验字符串是否为数字
    goodsList.forEach(
        o -> {
          if (!StringUtilsXiao.isNumericInt(o.getNumber())
              || !StringUtilsXiao.isNumeric(o.getPrice())) {
            throw new RuntimeException("请查看数量填写是否为整数， 单价填写是否为小数或者整数！");
          }
          if (StringUtilsXiao.isBlank(o.getEntityImgUrl())) {
            throw new RuntimeException("请上传实体图片！");
          }
          if (StringUtilsXiao.isBlank(o.getGoodsName())) {
            throw new RuntimeException("请填写资产名称！");
          }

          if (StringUtilsXiao.isBlank(o.getCompany())) {
            throw new RuntimeException("请填写计量单位！");
          }

          if (StringUtilsXiao.isBlank(o.getModel())) {
            throw new RuntimeException("请填写规格型号！");
          }

          if (StringUtilsXiao.isBlank(o.getEntityImgUrl())) {
            throw new RuntimeException("请上传实体图片！");
          }

          if (StringUtilsXiao.isBlank(o.getPLiable())) {
            throw new RuntimeException("请上传实体图片！");
          }
          if (StringUtilsXiao.isBlank(o.getPLiable())) {
            throw new RuntimeException("请填写保管人！");
          }
          // 关联单号
          o.setDateNoId(dateNo.getId());
        });
    // 插入航材详细信息
    boolean b = goodsService.saveOrUpdateBatch(goodsList);

    if (!b) {
      return $.error("修改成功");
    }
    return $.success("修改失败");
  }
  /**
   * 删除一条DateNo
   *
   * @param ids 前端传进的ID
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel delDateNos(List ids) {

    int i = baseMapper.deleteBatchIds(ids);

    return $.success(i);
  }

  /**
   * 分页查询DateNo
   *
   * @param page 页码
   * @param limit 查几条
   * @param dateNo 前端传进的参数
   * @return 返回统一分页信息
   */
  @Override
  public ResultPage findDateNoByPage(Integer page, Integer limit, DateNo dateNo) {
    Map<String, Object> paramMap = new HashMap<>();
    page = page == null ? 1 : page;
    limit = limit == null ? 20 : limit;

    paramMap.put("page", (page - 1) * limit);
    paramMap.put("limit", limit);
    paramMap.put("dateNo", dateNo);

    if (!StringUtilsXiao.isBlank(dateNo.getPurchaseDate())) {

      String[] purchaseDate = dateNo.getPurchaseDate().split(",");

      if (purchaseDate[0].equals(purchaseDate[1])) {
        purchaseDate[1] = String.valueOf((Long.valueOf(purchaseDate[1]) + 24 * 60 * 60 * 1000) - 1);
      }

      paramMap.put("purchaseDateStart", purchaseDate[0]);
      paramMap.put("purchaseDateEnd", purchaseDate[1]);
    }
    if (!StringUtilsXiao.isBlank(dateNo.getCreateTime())) {
      String[] createTime = dateNo.getCreateTime().split(",");

      if (createTime[0].equals(createTime[1])) {
        createTime[1] = String.valueOf((Long.valueOf(createTime[1]) + 24 * 60 * 60 * 1000) - 1);
      }
      paramMap.put("createTimeStart", createTime[0]);
      paramMap.put("createTimeEnd", createTime[1]);
    }

    List<DateNo> list = baseMapper.selectMyPage(paramMap);
    Integer count = baseMapper.countMyPage(paramMap);
    ResultPage<DateNo> resultPage = new ResultPage<>();
    resultPage.setCode(200);
    resultPage.setCount(count);
    resultPage.setMsg("成功");
    resultPage.setData(list);
    return resultPage;
  }

  // 隔离级别 可重复读取
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  @Override
  public ApiResultModel approved(Integer id) {
    boolean update =
        this.update(
            new LambdaUpdateWrapper<DateNo>()
                .set(DateNo::getApprovalState, "2")
                .eq(DateNo::getId, id));

    if (!update) {

      return $.error("提交失败！");
    }

    return $.success("审批成功");
  }

  private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd");

  /**
   * 下载word 需要的数据
   *
   * @param dateNoId
   * @return
   */
  @Override
  public Map downDocDateNoAllFixed(Integer dateNoId) {
    // 查询响应的数据 单号下所有的物品
    DateNo dateNo = selectDateNoByIdDateNo(dateNoId);
    // 判断订单是否存在
    if (dateNo == null) {
      throw new RuntimeException("该单号不存在！");
    }

    // 判断订单是否已通过审核
    if (!dateNo.getApprovalState().equals("2")) {
      throw new RuntimeException("该单号审核未通过！");
    }

    // 获取所有的商品
    List<Goods> fixeds = dateNo.getGoodsList();

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("department", "Jeeg"); // 复核
    map.put("person", "JueYue"); // 长度
    map.put("auditPerson", "JueYue");
    map.put("time", format.format(new Date()));
    map.put("date", new Date());

    // 查询对应的 单位名称
    //  Unit unit = unitService.getOne(new LambdaQueryWrapper<Unit>().eq(Unit::getId,
    // dateNo.getAffiliatedUnits()));

    map.put("affiliatedUnits", dateNo.getAffiliatedUnitsName());

    double numbers = 0;

    double prices = 0;

    for (Goods o : fixeds) {
      String assetsSource = sysDictService.selectByDatasourceKey("获取方式", dateNo.getAssetsSource());

      o.setAssetsSource(assetsSource);
      if (o.getGoodsType().equals("1")) {
        o.setInitNumber(Double.valueOf(o.getCount()));
      }

      Double number = o.getInitNumber();
      double price = Double.parseDouble(o.getPrice());

      o.setPrice(String.format("%.2f", price));

      double sum = number * price;

      numbers += number;
      prices += sum;
      o.setSumMoney(String.format("%.2f", sum) + "".trim());
    }

    map.put("fixeds", fixeds);

    //        numbers =new BigDecimal(numbers).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    map.put("nums", numbers);

    map.put("prices", String.format("%.2f", prices));

    return map;
  }
}
